#include "BinaryReader.h"

BinaryReader::BinaryReader():m_Open(false)
{
}

BinaryReader::BinaryReader(tstring filename):m_FileName(filename),m_Open(false)
{
}

BinaryReader::~BinaryReader(void)
{
}

bool BinaryReader::Open()
{
	m_File.open(m_FileName.c_str(),std::ios::binary);
	m_Open = m_File.is_open();
	return m_Open;
}

void BinaryReader::Close()
{
	if ( m_Open ){
		m_Open = false;
		m_File.close();
	}
}

int BinaryReader::ReadBigInt()
{
	static char bytes[4];
	//m_File.read(heade
	m_File.read(bytes,4);
	int result =0;
	for (int i =0; i< 4;i++){
		result <<=8;
		result+= bytes[i];
	}
	return result;
}
	
int BinaryReader::ReadLittleInt()
{
	int result;
	m_File.read((char*)&result,4);
	return result;
}

short BinaryReader::ReadLittleShort()
{
	short result;
	m_File.read((char*)&result,2);
	return result;
}

unsigned short BinaryReader::ReadLittleUShort()
{
	unsigned short result;
	m_File.read((char*)&result,2);
	return result;
}

float BinaryReader::ReadLittleFloat()
{
	float result;
	m_File.read((char*)&result,sizeof(float));
	return result;
}
	
double BinaryReader::ReadLittleDouble()
{
	double result;
	m_File.read((char*)&result,8);
	return result;
}

int BinaryReader::ReadByte(){
	return m_File.get();
}

tstring BinaryReader::ReadAsciiString()
{
	char buf[200];
	m_File.getline(buf,200,_T('\0'));
	//size_t count = m_File.gcount();
	string result(buf);
	return tstring(result.begin(),result.end());
}

void BinaryReader::Skip(int nrOfBytes){
	m_File.seekg(nrOfBytes, ios::cur);
}

tstring BinaryReader::ReadString()
{
	int encoding; // 1 or 2
	m_File.read((char*)&encoding,sizeof(int));
	int size;
	m_File.read((char*)&size,sizeof(int));

	if (encoding == 1){
		char* s = new char[size+1];
		m_File.read(s,size);
		s[size]=0;
		string result(s);
		// convert to tstring
		tstring value(result.begin(),result.end());
		delete[] s;
		return value;
	}else{
		wchar_t* s = new wchar_t[size/2+1];
		m_File.read((char*)s,size);
		s[size/2] = 0;
		tstring value(s);
		delete[] s;
		return value;
	}
}